package com.zr.rabbitmq.producer;

import com.zr.rabbitmq.dto.MessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 消息生产者，负责发送消息到RabbitMQ
 */
@Slf4j
@Component
public class MessageProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Value("${rabbitmq.exchange.direct}")
    private String directExchange;
    
    @Value("${rabbitmq.exchange.topic}")
    private String topicExchange;
    
    @Value("${rabbitmq.routing.sms}")
    private String smsRoutingKey;
    
    @Value("${rabbitmq.routing.email}")
    private String emailRoutingKey;

    /**
     * 发送短信消息
     */
    public void sendSmsMessage(MessageDTO message) {
        try {
            // 生成消息ID，用于消息确认
            String messageId = UUID.randomUUID().toString();
            message.setId(messageId);
            
            // 发送消息
            rabbitTemplate.convertAndSend(
                    directExchange, 
                    smsRoutingKey, 
                    message);
            
            log.info("短信消息发送成功，消息ID: {}", messageId);
        } catch (Exception e) {
            log.error("短信消息发送失败", e);
            throw new RuntimeException("短信消息发送失败", e);
        }
    }

    /**
     * 发送邮件消息
     */
    public void sendEmailMessage(MessageDTO message) {
        try {
            String messageId = UUID.randomUUID().toString();
            message.setId(messageId);
            
            rabbitTemplate.convertAndSend(
                    directExchange, 
                    emailRoutingKey, 
                    message, 
                    new CorrelationData(messageId)
            );
            
            log.info("邮件消息发送成功，消息ID: {}", messageId);
        } catch (Exception e) {
            log.error("邮件消息发送失败", e);
            throw new RuntimeException("邮件消息发送失败", e);
        }
    }

    /**
     * 发送通知消息到主题交换机
     */
    public void sendNoticeMessage(MessageDTO message, String routingKey) {
        try {
            String messageId = UUID.randomUUID().toString();
            message.setId(messageId);
            
            rabbitTemplate.convertAndSend(
                    topicExchange, 
                    routingKey, 
                    message, 
                    new CorrelationData(messageId)
            );
            
            log.info("通知消息发送成功，消息ID: {}, 路由键: {}", messageId, routingKey);
        } catch (Exception e) {
            log.error("通知消息发送失败", e);
            throw new RuntimeException("通知消息发送失败", e);
        }
    }
}
